# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# coding=utf-8
# -*- coding=utf-8 -*-

import os
from xpinyin import Pinyin
import re
import shutil
import glob

path = 'D:\poems\\all_poems'
poem_buf = ''
cnt = 0

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.

def is_digital(s):
    return s.isdigit()

def is_ci(poem_title):
    # coding=utf-8
    cipimings = [u'沁园春', u'水调歌头', u'采桑子',u'清平乐',u'念奴娇',u'千秋岁',u'天仙子',u'青门引',u'木兰花',u'剪牡丹',u'归朝欢',u'系裙腰',u'行香子',u'江城子',u'鹧鸪天',u'临江仙',u'贺新郎',u'定风波',u'西江月',u'永遇乐',u'满庭芳',u'浣溪沙',u'菩萨蛮',u'一丛花',u'玉楼春',u'鹤冲天',u'玉蝴蝶',u'雨霖铃',u'浪淘沙',u'踏莎行',u'蝶恋花',u'破阵子',u'渔家傲',u'桂枝香',u'秦楼月',u'望江梅',u'望江南',u'相见欢',u'摊破浣溪沙',u'谒金门',u'卜算子',u'摸鱼儿',u'酹江月',u'霜天晓角',u'山坡羊',u'鹊桥仙',u'如梦令',u'小重山',u'钗头凤',u'关山月',u'点绛唇',u'南歌子',u'醉花阴',u'一剪梅',u'声声慢',u'生查子',u'满江红',u'丑奴儿',u'水龙吟',u'扬州慢',u'好事近',u'天净沙']
    for s in cipimings:
        if poem_title.replace(s, '') != poem_title:
            return True
    return False

def is_jueju(poem_content, word_num):
    tmp_buf = re.sub('《|》|“|‘|`|\'|"', '', poem_content)
    print('1. is_%djue tmp_buf=%s' % (word_num, tmp_buf))
    tmp_buf = re.sub('，|。|？|！|、|·|；|：|~|\\?|,|\.|;|:', ' ', tmp_buf)
    print('2. is_%djue tmp_buf=%s' % (word_num, tmp_buf))
    p = Pinyin()
    tmp_list = p.get_initials(tmp_buf, splitter='', with_retroflex=False).split()
    print('3. is_%djue tmp_list=%s' % (word_num, tmp_list))
    if len(tmp_list) == 4 and len(tmp_list[0]) == word_num and len(tmp_list[1]) == word_num and len(tmp_list[2]) == word_num and len(tmp_list[3]) == word_num:
        return True
    return False

def is_5jue(poem_content):
    return is_jueju(poem_content, 5)

def is_7jue(poem_content):
    return is_jueju(poem_content, 7)

def is_7lv(poem_content):
    word_num = 7

    tmp_buf = re.sub('《|》|“|‘|`|\'|"', '', poem_content)
    print('1. is_%dlv tmp_buf=%s' % (word_num, tmp_buf))
    tmp_buf = re.sub('，|。|？|！|、|·|；|：|~|\\?|,|\.|;|:', ' ', tmp_buf)
    print('2. is_%dlv tmp_buf=%s' % (word_num, tmp_buf))
    p = Pinyin()
    tmp_list = p.get_initials(tmp_buf, splitter='', with_retroflex=False).split()
    print('3. is_%dlv tmp_list=%s' % (word_num, tmp_list))

    if len(tmp_list) != 8:
        return False
    for i in range(0, 8):
        if len(tmp_list[i]) != 7:
            return False
    return True

def is_za_7yishang(poem_content):
    word_num = 7

    tmp_buf = re.sub('《|》|“|‘|`|\'|"', '', poem_content)
    print('1. is_%dyishang tmp_buf=%s' % (word_num, tmp_buf))
    tmp_buf = re.sub('，|。|？|！|、|·|；|：|~|\\?|,|\.|;|:', ' ', tmp_buf)
    print('2. is_%dyishang tmp_buf=%s' % (word_num, tmp_buf))
    p = Pinyin()
    tmp_list = p.get_initials(tmp_buf, splitter='', with_retroflex=False).split()
    print('3. is_%dyishang tmp_list=%s' % (word_num, tmp_list))

    for i in range(0, len(tmp_list)):
        if len(tmp_list[i]) >= 7:
            return True
    return False

def is_za_456(poem_content):
    return True

def generate_a_poem(name, content, title):
    tmp_buf = re.sub('《|》|，|。|？|！|、|·|；|：|~|“|‘|\\?|`|,|\.|;|:|\'|"', '', content)
    print('content = %s' % content)
    print('tmp_buf = %s' % tmp_buf)
    p = Pinyin()
    name = p.get_pinyin(tmp_buf, splitter=' ', convert='lower').split()[0] + name
    f = open(name, "w", encoding="utf-8", newline='\r\n')

    buf = content + (title + '\n')

    f.write(buf)
    f.close()
    if is_ci(title):
        shutil.move(name, 'ci')
    elif is_5jue(content):
        shutil.move(name, '5jue')
    elif is_7jue(content):
        shutil.move(name, '7jue')
    elif is_7lv(content):
        shutil.move(name, '7lv')
    elif is_za_7yishang(content):
        shutil.move(name, 'za_7yishang')
    else:
        shutil.move(name, 'za_456')

def cat_dir_files(dir_name):
    dest_path = dir_name + '_cat.txt'
    shutil.rmtree(dest_path, ignore_errors=True)
    dest_f = open(dest_path, 'ab')
    for file_path in glob.glob(dir_name + '\\*.txt'):
        f = open(file_path, 'rb')
        buf = f.read()
        f.close()
        dest_f.write(buf)
    dest_f.close()

def is_poem_title_line(line):
    for c in line:
        if c == "，" or c == "。" or c == "；" or c == "？" or c == "！" or c == "、":
            return False
        elif c == "," or c == ";" or c == "?" or c == "!":
            return False
    print("==== %s is_poem_title_line ====" % line)
    return True

def classify_poems():
    global poem_buf
    global cnt
    poem_index = 1
    poem_title = ''
    is_poem_title = False
    is_poem_title_head = False

    print('classify_poems')
    print('=======> take all poems to a directory')

    print('Current dir is ' + os.getcwd())
    f = open("1000-poems-sort-copy.txt", "r", encoding="utf-8")
    while True:
        # while poem_index < 20:
        line = f.readline()
        if line:
            line = line.strip()
            # line = line.replace('\n', '')
            print(line)
            if is_digital(line[0]):
                print("%s is digit" % (line[0]))
                is_poem_title_head = True
                is_poem_title = True
                if len(poem_buf) != 0:
                    generate_a_poem(str(poem_index) + '.txt', poem_buf, poem_title)
                    poem_buf = ''
                    poem_title = ''
                    poem_index += 1
            if is_poem_title_head or (is_poem_title and is_poem_title_line(line)):
                is_poem_title_head = False
                if len(poem_title) == 0:
                    poem_title += line
                else:
                    poem_title += ' ' + line
            else:
                is_poem_title = False
                poem_buf += (line + '\n')
        else:
            break

    f.close()

    if len(poem_buf) != 0:
        generate_a_poem(str(poem_index) + '.txt', poem_buf, poem_title)

def sort_poems():
    print('sort_poems')

def prepare1():
    os.chdir(path)

def prepare2():
    shutil.rmtree("5jue", ignore_errors=True)
    shutil.rmtree("7jue", ignore_errors=True)
    shutil.rmtree("7lv", ignore_errors=True)
    shutil.rmtree("ci", ignore_errors=True)
    shutil.rmtree("za_7yishang", ignore_errors=True)
    shutil.rmtree("za_456", ignore_errors=True)

    os.mkdir("5jue")
    os.mkdir("7jue")
    os.mkdir("7lv")
    os.mkdir("ci")
    os.mkdir("za_7yishang")
    os.mkdir("za_456")

def finish():
    for dir_name in ['5jue', '7jue', '7lv', 'ci', 'za_7yishang', 'za_456']:
        cat_dir_files(dir_name)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    print_hi('PyCharm')
    prepare1()
    prepare2()
    classify_poems()
    sort_poems()
    finish()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
